<template>
  <a-modal :open="open" width="1050px" destroy-on-close title="手术登记" centered @cancel="onCancel">
    <div class="flex">
      <div class="w-2/5 pr-2">
        <SelectTable
          v-model:value="formState.brName"
          type="手术预约"
          placeholder="姓名/助记码/卡号/手机号/证件号码"
          :disabled="rowData.lsh"
          custom-input
          :maxlength="20"
          empty-close
          @select="onSelectPatient"
        />
        <UserCard :user-data="userInfo" class="mt-3">
          <div class="flex flex-col justify-between px-5">
            <div class="flex justify-between items-center mt-2">
              <LabelValue label-align="right" :label-width="120" label="负责人" :value="userInfo.brFzrName" />
              <LabelValue label-align="right" :label-width="120" label="咨询师" :value="userInfo.brZxsName" />
              <LabelValue label-align="right" :label-width="120" label="业务员" :value="userInfo.brYwyName" />
            </div>
            <a-descriptions class="mt-3" :column="1">
              <a-descriptions-item label="关注项目" class="w-full pb-5">
                <a-select
                  v-model:value="formState.brZlxm"
                  :disabled="userInfo.brZlxm"
                  class="w-full"
                  placeholder="请选择"
                  :options="interestProject"
                  allow-clear
                  mode="multiple"
                  max-tag-count="responsive"
                  @change="onChangeSelect"
                />
              </a-descriptions-item>
              <a-descriptions-item label="客户来源" class="w-full">
                <SelectCustomerSource v-model:value="formState.brly" class="w-full" @change="onChangeSelect" />
              </a-descriptions-item>
            </a-descriptions>
            <a-form-item class="w-full">
              <div v-if="tagsList.length > 0" class="flex flex-wrap">
                <div v-for="item in tagsList" :key="item.id" class="tag-item flex items-center mb-2">
                  <div class="tag-item-label truncate max-w-[160px]">{{ item.labelName }}</div>
                  <div class="tag-item-value truncate max-w-[160px]">{{ item.itemNameString }}</div>
                </div>
                <div>
                  <a-button @click="openTagsModal = true"><FormOutlined /></a-button>
                </div>
              </div>
              <a-button v-else type="primary" ghost :disabled="!userInfo.brId" @click="openTagsModal = true">添加标签</a-button>
            </a-form-item>
          </div>
        </UserCard>
      </div>
      <div class="w-3/5">
        <a-form :model="formState" class="form-style-flex">
          <a-form-item label="手术日期" v-bind="validateInfos.oprDate" class="w-1/2">
            <a-date-picker v-model:value="formState.oprDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </a-form-item>
          <a-form-item label="手术时间" class="w-1/2">
            <a-time-picker v-model:value="formState.oprTime" value-format="HH:mm" format="HH:mm" @keydown.enter="onTimeEnter" />
          </a-form-item>
          <a-form-item label="右眼手术" class="w-full">
            <!-- :select-only-one="formState.brId && !formState.isSelectedOd" -->
            <SelectTable
              v-model:value="formState.odmc"
              type="手术收费项目"
              :search-params="{ brId: formState.brId, bw: '右眼', jklb: '5' }"
              no-page
              auto-mark
              allow-clear
              :disabled="!formState?.brId"
              @select="onSelectOd"
            />
          </a-form-item>
          <!-- <a-form-item label="" class="w-1/2 pl-4">
            <span> 标准金额：￥{{ formatAmount(formState.rightBzzje || 0) }}</span>
            <span class="pl-4"> 实际金额：￥{{ formatAmount(formState.rightSjje || 0) }}</span>
          </a-form-item> -->
          <a-form-item label="左眼手术" class="w-full">
            <!-- :select-only-one="formState.brId && !formState.isSelectedOs" -->
            <SelectTable
              v-model:value="formState.osmc"
              type="手术收费项目"
              :search-params="{ brId: formState.brId, bw: '左眼', jklb: '5' }"
              no-page
              auto-mark
              allow-clear
              :disabled="!formState.brId"
              @select="onSelectOs"
            />
          </a-form-item>
          <!-- <a-form-item label="" class="w-1/2 pl-4">
            <span> 标准金额：￥{{ formatAmount(formState.leftBzzje || 0) }}</span>
            <span class="pl-4"> 实际金额：￥{{ formatAmount(formState.leftSjje || 0) }}</span>
          </a-form-item> -->
          <a-form-item label="手术医生" v-bind="validateInfos.ssys" class="w-1/2">
            <SelectTable v-model:value="formState.ssys" type="医生" custom-input empty-close @select="onSelectEmp" />
          </a-form-item>
          <a-form-item v-if="isRequired" v-bind="validateInfos.oprSn" :label="isBJMSG ? '病历号' : '病案号'" class="w-1/2">
            <a-input-group compact>
              <a-input v-model:value="formState.oprSn" :disabled="!isAllowModify" style="width: calc(100% - 64px)" placeholder="请生成病案号" />
              <a-button type="primary" :disabled="!formState?.brId || isAutoCode" @click="onClickMedical">生成</a-button>
            </a-input-group>
            <!-- 
            <a-input v-model:value="formState.oprSn" :disabled="!isAllowModify" class="w-[80%]" placeholder="请生成病案号" />
            <a-button type="link" :disabled="!formState?.brId || isAutoCode" class="w-[20%]" @click="onClickMedical">生成</a-button> -->
          </a-form-item>
          <!-- <a-form-item v-else label="病案号" v-bind="validateInfos.oprSn" class="w-full">
            <a-input v-model:value="formState.oprSn" :disabled="!isAllowModify" class="w-[80%]" placeholder="请生成病案号" />
            <a-button type="link" :disabled="!formState?.brId || isAutoCode" class="w-[20%]" @click="onClickMedical">生成</a-button>
          </a-form-item> -->
          <a-form-item label="术后提示" class="w-full">
            <a-input v-model:value="formState.postoperativeTipsUrl" placeholder="请输入术后提示URL" />
          </a-form-item>
          <!-- <a-form-item label="押金用途" class="w-full">
              <a-select
                v-model:value="formState.zzys"
                :options="depositDoctor"
                placeholder="请选择"
                :field-names="{ label: 'pathName', value: 'id' }"
                @focus="getExpressMode"
                @change="onChangexpressMode"
              />
            </a-form-item> -->
          <a-form-item label="备注" class="w-full">
            <a-textarea v-model:value="formState.memo" :rows="6" placeholder="请输入" />
          </a-form-item>
        </a-form>
      </div>
    </div>
    <div v-if="isOperationDetail && editType" class="w-full border-t-2 pt-2">
      <a-form :model="formState" class="form-style-flex" :label-col="{ style: { width: '100px' } }">
        <div class="flex w-full">
          <a-form-item label="术前诊断" class="w-1/3">
            <SelectTable v-model:value="formState.diagnosisPreoprName" type="术前诊断" @select="(selected) => onSelectDiagnosis(selected)" />
            <!-- diagnosisPreopr -->
          </a-form-item>
          <a-form-item label="麻醉方式" class="w-1/3">
            <SelectItem v-model:value="formState.anesthesiaMethod" type="DT00012" placeholder="请选择" allow-clear />
          </a-form-item>
        </div>
        <a-form-item label="右  拟桥" class="w-1/3">
          <a-input v-model:value="formState.odNj" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="DS" class="w-1/3">
          <a-input v-model:value="formState.odDs" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="DC" class="w-1/3">
          <a-input v-model:value="formState.odDc" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="左  拟桥" class="w-1/3">
          <a-input v-model:value="formState.osNj" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="DS" class="w-1/3">
          <a-input v-model:value="formState.osDs" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="DC" class="w-1/3">
          <a-input v-model:value="formState.osDc" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="右  mj/p" class="w-1/4">
          <a-input v-model:value="formState.odMjp" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="Z" class="w-1/4">
          <a-input v-model:value="formState.odZ" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="TP" class="w-1/4">
          <a-input v-model:value="formState.odTp" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="D" class="w-1/4">
          <a-input v-model:value="formState.odD" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="左  mj/p" class="w-1/4">
          <a-input v-model:value="formState.osMjp" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="Z" class="w-1/4">
          <a-input v-model:value="formState.osZ" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="TP" class="w-1/4">
          <a-input v-model:value="formState.osTp" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="D" class="w-1/4">
          <a-input v-model:value="formState.osD" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="右眼并发症" class="w-1/3">
          <a-input v-model:value="formState.odComplication" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="左眼并发症" class="w-1/3">
          <a-input v-model:value="formState.osComplication" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="右眼手术记录" class="w-full">
          <a-input v-model:value="formState.odOprRecord" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="左眼手术记录" class="w-full">
          <a-input v-model:value="formState.osOprRecord" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </div>
    <template #footer>
      <div class="flex justify-between">
        <div class="pl-[40%]">
          <span> 标准金额：￥{{ formatAmount((formState.leftBzzje || 0) + (formState.rightBzzje || 0)) }}</span>
          <span class="pl-4"> 实际金额：￥{{ formatAmount((formState.leftSjje || 0) + (formState.rightSjje || 0)) }}</span>
        </div>
        <div>
          <a-button @click="onCancel()">取消</a-button>
          <a-button type="primary" :disabled="!isCompleted" @click="onOk">保存</a-button>
        </div>
      </div>
    </template>
    <TagsModal v-model:open="openTagsModal" :tag-data="tagsList" @success="onSelectTags" />
  </a-modal>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { FormOutlined } from '@ant-design/icons-vue'
import { groupBy } from 'lodash-es'
import dayjs from 'dayjs'
import { post } from '@/utils/request'
import SelectTable from '@/components/SelectTable'
import { formatAmount } from '@/utils/format'
import UserCard from '@/components/UserCard'
import TagsModal from '@/components/business/TagsModal'
import SelectItem from '@/components/SelectItem'
import { getSystemConfig } from '@/utils/systemConfig'

const emit = defineEmits(['update:open', 'success'])

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  editType: {
    type: Boolean,
    default: false
  },
  recording: {
    type: Boolean,
    default: false
  }
})
const isRequired = getSystemConfig('OOS_OPERATION_REGISTER_ALLOW_NO_OPR_NUMBER') === '1' // '手术病案号是否必填', '0:不允许|1:允许'
// const isOperativeUrl = getSystemConfig('OOS_OPERATION_QR_CODE_URL') // 眼科手术腕带二维码URL
const isOperationDetail = ref(true)
// const isEye = ref(true)
const isAutoCode = ref(true)
const isAllowModify = ref(false)
const openTagsModal = ref(false)
const formState = ref({
  oprDate: '',
  oprTime: '',
  ssys: '',
  oprSn: '',
  osmc: '',
  osOprBh: '',
  odmc: '',
  odOprBh: '',
  brId: '',
  brName: '',
  zdmc: ''
})
// const depositDoctor = ref([])
const userInfo = ref({})
const interestProject = ref([])
const tagsList = ref([])
const rulesActive = ref()
const saveUrl = ref('/operation/opex/doRegisterOperation')
const rulesState = ref({
  oprDate: [{ required: true, message: '请选择手术日期' }],
  // oprTime: [{ required: true, message: '请选择手术时间' }],
  ssys: [{ required: true, message: '请选择手术医生' }],
  oprSn: [{ required: true, message: '请生成病案号' }]
})
const rulesStateNo = ref({
  oprDate: [{ required: true, message: '请选择手术日期' }],
  // oprTime: [{ required: true, message: '请选择手术时间' }],
  ssys: [{ required: true, message: '请选择手术医生' }]
})

rulesActive.value = isRequired ? rulesState.value : rulesStateNo.value
const { resetFields, clearValidate, isCompleted, validateInfos } = useForm(formState, rulesActive)

const onSelectEmp = (select) => {
  formState.value = {
    ...formState.value,
    oprEmpId: select.empId,
    ssys: select.empName
  }
}
const onSelectDiagnosis = (select) => {
  formState.value.diagnosisPreopr = select.zddm
  formState.value.diagnosisPreoprName = select.zdmc
}
const onSelectPatient = (select) => {
  formState.value.oprSn && (formState.value.oprSn = '')
  formState.value = {
    ...formState.value,
    ...select,
    brNames: select.brName
  }
  userInfo.value = {
    ...select
  }
  isAutoCode.value && onClickMedical()
  !select.brZlxm && (formState.value.brZlxm = [])
  !select.brly && (formState.value.brly = undefined)
  getTagsList()
  // const finalUrl = isOperativeUrl.replace('{KHBH}', '111') // 处理url，替换入参
}

const onSelectOs = (select) => {
  formState.value = {
    ...formState.value,
    isSelectedOs: true,
    osmc: select.mc,
    osOprBh: select?.bh || select?.sfxmbh,
    osAdvId: select.id,
    leftBzzje: select.bzzje,
    leftSjje: select.sjje
  }
}
const onSelectOd = (select) => {
  formState.value = {
    ...formState.value,
    isSelectedOd: true,
    odmc: select.mc,
    odOprBh: select?.bh || select?.sfxmbh,
    odAdvId: select.id,
    rightBzzje: select.bzzje,
    rightSjje: select.sjje
  }
}

const getTagsList = async () => {
  const { code, data, msg } = await post('/common/label/getLableListByPatientld', { brId: userInfo.value.brId })
  if (code !== 0) return message.error(msg || '获取标签失败')
  tagsList.value = groupsList(data, 'labelId')
  userInfo.value.labelList = data.map((tag) => tag.itemId)
}
const groupsList = (list) => {
  const groupedByLabelId = groupBy(list, 'labelId')
  const result = []
  for (const labelId in groupedByLabelId) {
    const items = groupedByLabelId[labelId]
    result.push({
      labelId,
      labelName: items[0].labelName,
      itemId: items.map((item) => item.itemId),
      itemName: items.map((item) => item.itemName),
      itemNameString: items.map((item) => item.itemName).join(', ')
    })
  }
  return result
}
const onSelectTags = async (tags = []) => {
  userInfo.value.labelList = tags.map((tag) => tag.id)
  tagsList.value = groupsList(tags)
  const res = await post('/operation/opex/doAddLabelList', { brId: userInfo.value.brId, labelList: userInfo.value.labelList })
  if (res.code !== 0) return message.error(res.msg)
}
const getInterestProject = async () => {
  const { data, code } = await post('/operation/opex/getDictFocusItemList', { zjm: '' })
  if (code !== 0) return message.error(code || '获取数据失败')
  interestProject.value = data.map((item) => {
    return {
      label: item.itemName,
      value: item.id
    }
  })
}
const onChangeSelect = async () => {
  if (formState.value.brName) {
    formState.value.jksy = 0
    const res = await post('/common/patient/savePatientInfo', formState.value)
    if (res.code !== 0) return message.error(res.msg)
  }
}

// :disabled-date="disabledDate"
// const disabledDate = (current) => {
//   // 禁用今天之前的日期
//   return current && current < new Date(new Date().toDateString())
// }

const getSurgicalRecords = async () => {
  const res = await post('/operation/opex/getOperationMedicalRecordInfo', { oprLsh: formState.value.lsh })
  if (res.code !== 0) return message.error(res.msg)
  formState.value = {
    ...formState.value,
    ...res.data
  }
}

// 点击生成病案号
const onClickMedical = async () => {
  if (formState.value.oprSn) return message.error('手术病案号已存在')
  // if (!formState.value.osOprBh && !formState.value.odOprBh) return message.error('必须选择一种手术')
  const res = await post('/operation/opex/doGenerateOperationId', {
    bqflag: 2,
    osOprBh: formState.value.osOprBh,
    odOprBh: formState.value.odOprBh,
    brId: formState.value.brId
  })
  if (res.code !== 0) return message.error(res.msg)
  formState.value.oprSn = res.data?.oprSn
}

const onOk = async () => {
  if (!formState.value.brName) return message.error('姓名不能为空')
  if (!formState.value.osOprBh && !formState.value.odOprBh) return message.error('必须选择一种手术')
  if (isRequired) {
    if (!formState.value.oprSn) return message.error('请点击生成病案号')
  }
  if (isOperationDetail.value && props.editType) {
    saveUrl.value = '/operation/opex/doSaveOperationMedicalRecord'
    formState.value = {
      ...formState.value,
      oprLsh: formState.value.lsh
    }
  }

  const res = await post(saveUrl.value, formState.value)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  emit('success')
  onCancel()
}

const onCancel = () => {
  saveUrl.value = '/operation/opex/doRegisterOperation'
  emit('update:open', false)
  resetFields()
}

const getUserInfo = async (brId) => {
  const { code, data, msg } = await post('/outp/mzdj/getPatientInfoList', { brId: brId, pageNum: 1, pageSize: 10 })
  if (code !== 0) return message.error(msg)

  userInfo.value = {
    ...data[0]
  }
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      getInterestProject()
      if (props.rowData?.brId) {
        formState.value = { ...props.rowData }
        getUserInfo(props.rowData?.brId)
        userInfo.value.brId = props.rowData?.brId
        formState.value.brZlxm = formState.value.brZlxm || []
        formState.value.brly = formState.value.brly || undefined

        getTagsList()
        clearValidate()
      } else {
        userInfo.value = {}
        formState.value = {}
        // formState.value.postoperativeTipsUrl = isOperativeUrl
      }
      if (isOperationDetail.value && props.recording) getSurgicalRecords()
      if (props.rowData?.isRegister) {
        isAutoCode.value && onClickMedical()
      }
    }
  }
)
watch(
  () => formState.value.odmc,
  (val) => {
    if (!val) {
      if (!formState.value.odmc) {
        formState.value.odOprBh = ''
      }
    }
  }
)
watch(
  () => formState.value.osmc,
  (val) => {
    if (!val) {
      if (!formState.value.osmc) {
        formState.value.osOprBh = ''
      }
    }
  }
)
const onTimeEnter = (e) => {
  const timeString = e.target.value
  const regex1 = /^\d{4}$/ // 匹配HHmm格式
  const isValidTime = regex1.test(timeString)
  if (isValidTime) {
    //HHmm to HH:mm
    formState.value.oprTime = dayjs(timeString, 'HHmm').format('HH:mm')
    e.target.blur()
  }
}
const isBJMSG = getSystemConfig('GHDJYS') === '4' //是否北京茗视光
onMounted(() => {
  isOperationDetail.value = getSystemConfig('SHOW_OO_OPERATION_REGISTER_DETAIL') === '1' // 手术登记详细信息
  // isEye.value = getSystemConfig('OO_OPERATION_REGISTER_CHOOSE_MODE') === '0' // 手术0：处置1：全部手术
  isAutoCode.value = getSystemConfig('OPERATION_NO_AUTO_GENERATE') === '1' // 病案号自动生成，0：手动，1：自动
  isAllowModify.value = getSystemConfig('OPERATION_NO_ALLOW_MODIFY') === '1' // '手术病案号允许手动修改', '0:不允许|1:允许'
})
</script>

<style lang="less" scoped>
.ant-descriptions {
  :deep(.ant-descriptions-item-label) {
    padding-top: 3px;
  }
}
.tag-item {
  margin-right: 8px;
  overflow: hidden;
  border: 1px solid var(--primary-color);
  border-radius: 8px;
  .tag-item-label {
    padding: 4px 12px;
    color: #fff;
    background-color: var(--primary-color);
  }
  .tag-item-value {
    padding: 4px 12px;
  }
}
.ant-tag-checkable-checked {
  color: #fff;
  background-color: var(--primary-color);
}
</style>
